﻿using System;
using System.Collections.Generic;
using Android;
using Android.App;
using Android.Content.PM;
using Android.OS;
using Android.Widget;
using Com.Baidu.Speech;
using Com.Baidu.Speech.Asr;
using Newtonsoft.Json;

namespace VoiceApp
{
    [Activity(Label = "VoiceApp", MainLauncher = true)]
    public class MainActivity : Activity
    {
        public static IEventManager asr;

        TextView CommandList;
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            initPermission();

            asr = EventManagerFactory.Create(this, "asr");

            Button btnStart = FindViewById<Button>(Resource.Id.btnStart);
            CommandList = FindViewById<TextView>(Resource.Id.txtMsg);

            btnStart.Click += BtnStart_Click;

            asr.RegisterListener(new MyListener(CommandList));
        }

        bool running = false;
        private void BtnStart_Click(object sender, EventArgs e)
        {
            running = !running;
            if (running)
            {
                (sender as Button).Text = "Stop";
                //CommandList.Text = "Waiting command";
                Load_Grammar_Engine();
                Asr_Start();
            }
            else
            {
                (sender as Button).Text = "Start";
                //CommandList.Text = "Processing ...";
                Asr_Stop();
                Unload_Grammar_Engine();
            }
        }

        void Asr_Start()
        {
            String json = "{\"accept-audio-data\":false,\"disable-punctuation\":false,\"accept-audio-volume\":true,\"pid\":1736,\"decoder\":2}";
            asr.Send(SpeechConstant.AsrStart, json, null, 0, 0);
        }

        void Asr_Stop()
        {
            asr.Send(SpeechConstant.AsrStop, null, null, 0, 0); // 发送停止录音事件，提前结束录音等待识别结果
        }

        void Asr_Cancel()
        {
            asr.Send(SpeechConstant.AsrCancel, null, null, 0, 0); // 取消本次识别，取消后将立即停止不会返回识别结果
        }

        void Load_Grammar_Engine()
        {
            var map = new
            {
                decoder = 2,
                grammar = "assets://baidu_speech_grammar.bsg" //"/data/user/0/VoiceApp.VoiceApp/baidu_speech_grammar.bsg"
            };

            //Hashtable map = new Hashtable();
            //map.Add(SpeechConstant.Decoder, 2); // 0:在线 2.离在线融合(在线优先)
            //map.Add(SpeechConstant.AsrOfflineEngineGrammerFilePath, "/sdcard/yourpath/baidu_speech_grammar.bsg"); // 设置离线命令词文件路径

            // 下面这段可选，用于生成SLOT_DATA参数， 用于动态覆盖ASR_OFFLINE_ENGINE_GRAMMER_FILE_PATH文件的词条部分
            //json json = new JSONObject();
            //json.put("name", new JSONArray().put("王自强").put("叶问")).put("appname", new JSONArray().put("手百").put("度秘"));
            //map.put(SpeechConstant.SLOT_DATA, json.toString());
            // SLOT_DATA 参数添加完毕

            string json = JsonConvert.SerializeObject(map);
            asr.Send(SpeechConstant.AsrKwsLoadEngine, json, null, 0, 0); // 加载离线引擎，使用离线命令词时使用，请在整个离线识别任务结束之后卸载离线引擎 
                                                                   // 此处开始你的识别流程，注意离线必须断网生效或者SDK无法连接百度服务器时生效，只能识别bsg文件里定义的短语。
                                                                   // 不再需要识别功能后，卸载离线引擎。再次需要识别功能的话，可以重复以上步骤。即依旧需要EventManager初始化之后，识别事件之前加载离线引擎。            
        }

        void Unload_Grammar_Engine()
        {
            asr.Send(SpeechConstant.AsrKwsUnloadEngine, null, null, 0, 0);
        }

        protected override void OnDestroy()
        {
            base.OnDestroy();            
        }

        /**
         * android 6.0 以上需要动态申请权限
         */
        private void initPermission()
        {
            string[] permissions = new string[] {
                Manifest.Permission.RecordAudio,
                Manifest.Permission.AccessNetworkState,
                Manifest.Permission.Internet,
                Manifest.Permission.ReadPhoneState,
                Manifest.Permission.WriteExternalStorage
            };            

            List<String> toApplyList = new List<String>();
            foreach (var perm in permissions)
            {
                if (Permission.Granted != CheckSelfPermission(perm))
                {
                    toApplyList.Add(perm);
                    //进入到这里代表没有权限.
                }
            }

            if (toApplyList.Count > 0)
            {
                RequestPermissions(toApplyList.ToArray(), 735);
            }
        }


        public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults)
        {
            // 此处为android 6.0以上动态授权的回调，用户自行实现。
        }
    }

    class MyListener : Java.Lang.Object, IEventListener
    {
        TextView CommandList;
        public MyListener(TextView commandList)
        {
            CommandList = commandList;
        }

        public void OnEvent(string p0, string p1, byte[] p2, int p3, int p4)
        {
            if (p0 == SpeechConstant.CallbackEventAsrReady)
            {
                CommandList.Text += "CallbackEventAsrReady\n";
            }
            else if (p0 == SpeechConstant.CallbackEventAsrFinish)
            {
                CommandList.Text += "CallbackEventAsrFinish\n";
            }
            else if (p0 == SpeechConstant.CallbackEventAsrPartial)
            {
                CommandList.Append("\n" + p1);
            }

            //CommandList.Append("\n" + p1);
        }

        #region IDisposable Support
        private bool disposedValue = false; // To detect redundant calls

        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    // TODO: dispose managed state (managed objects).
                }

                // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
                // TODO: set large fields to null.

                disposedValue = true;
            }
        }

        // TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources.
        // ~MyListener() {
        //   // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
        //   Dispose(false);
        // }

        // This code added to correctly implement the disposable pattern.
        public void Dispose()
        {
            // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
            Dispose(true);
            // TODO: uncomment the following line if the finalizer is overridden above.
            // GC.SuppressFinalize(this);
        }
        #endregion

    }
}

